package com.shunwang.query_sql.tool.exception;

import com.shunwang.query_sql.tool.api.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public R<String> handleAllExceptions(Exception ex) {
        log.error("系统异常: {}", ex.getMessage(), ex);
        return R.data(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage(), null);
    }

    /**
     * 处理404 Not Found
     */
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerCustomizer() {
        return factory -> factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
    }

    @RequestMapping("/error/404")
    public R<Object> handleNotFound() {
        return R.fail(HttpStatus.NOT_FOUND.value(), "资源未找到");
    }

}
